import {$dialog, $message, $notice, AutoTable, Button, i18n, Plc, PlcDate, PlcInput, PlcTextarea} from "plain-design";
import {useTableOption} from "../../modules/plain-design/useTableOption";
import {designPage, onMounted} from "@peryl/react-compose";
import {usePageService} from "../../modules/micro/usePageService";
import {MonacoEditor} from "../components/MonacoEditor";
import {http} from "../../modules/plain-design/http";
import {PlainObject} from "@peryl/utils/event";
import {MonacoLoader} from "../components/MonacoEditor/monaco.utils";
import {kebabCase} from "@peryl/utils/kebabCase";
import {copyToClipboard} from "@peryl/utils/copyToClipboard";

export default designPage(() => {

  // usePageTitle('查询列表')
  // usePageButton({ label: '保存', seq: 99, primary: true, handler: () => {$message.primary('保存');} });

  const { nav } = usePageService();

  const option = useTableOption({
    url: '/module',
    fill: true,
  });

  const copyDDLSql = (_moduleConfig: string) => {
    try {
      const moduleConfig = !_moduleConfig ? null : JSON.parse(_moduleConfig);
      if (!moduleConfig) {
        $notice.error(i18n.$intl('page.moduleListPage.invalidModuleConfig').d('模块配置信息不正确'));
        return;
      }
      const ddl = `
create table ${moduleConfig.tableName}
(
    id           varchar(50) default uuid()              not null comment '编号' primary key,
    created_at   datetime    default current_timestamp() null comment '创建时间',
    created_by   varchar(50)                             null comment '创建人id',
    updated_at   datetime    default current_timestamp() null comment '最后更新时间',
    updated_by   varchar(50)                             null comment '最后更新人id',

${Object.entries(moduleConfig.columns).map(([humpName,columnInfo]:[string,any])=>{
  if(['id','createdAt','createdBy','updatedAt','updatedBy'].indexOf(humpName)>-1){return  null;}
  if(columnInfo.query?.trim().length){
    return '';
  }
  return`\t${kebabCase(humpName).replace(/-/g,'_')}\t\t${(()=>{
    switch (columnInfo.valueType){
      case 'string':
        return 'varchar(50)';
      case 'number':
        return 'decimal';
      case 'date':
        return  'datetime';
      case 'datetime':
        return  'datetime';
      case 'time':
        return  'time';
    }
  })()}\tnull\tcomment\t'${columnInfo.front?.title}'`;
}).filter(Boolean).join(',\n')},
    constraint ${moduleConfig.tableName}_id_uindex
        unique (id)
) collate = utf8mb4_unicode_ci;
    `;
      copyToClipboard(ddl, () => $message(i18n.$intl('page.moduleListPage.alreadyCopy').d('已复制')));
    } catch (e) {
      console.error(e);
      $notice.error(i18n.$intl('page.moduleListPage.invalidModuleConfig').d('模块配置信息不正确'));
    }
  };

  const onClick = (row: any) => {
    let editValue = row.moduleConfig;
    $dialog({
      title: `${row.label || '未命名'}${!!row.code ? `(${row.code})` : ''}`,
      position: 'right',
      width: '750px',
      noContentPadding: true,
      confirmButton: true,
      cancelButton: true,
      confirmButtonText: i18n.$it('base.edit.save').d('保存'),
      render: () => (
        <MonacoEditor modelValue={editValue} onUpdateModelValue={(e: any) => {editValue = e;}} language="json"/>
      ),
      renderFoot: () => {
        return <Button key="copy" mode="text" style={{ order: '20' }} label={i18n.$intl('page.moduleListPage.copyTableDDLSql').d("复制建表语句")} onClick={() => copyDDLSql(editValue)}/>;
      },
      handleConfirm: async () => {
        try {
          JSON.parse(editValue);
        } catch (e) {
          $notice.error(i18n.$intl('page.moduleListPage.invalidJson').d("JSON格式不正确！"));
          return false;
        }
        const newRow = { ...row, moduleConfig: editValue };
        await http.post<{ row: PlainObject }>('/module/update', { row: newRow });
        await option.methods.pageMethods.load();
      },
    });
  };

  onMounted(() => {MonacoLoader.getMonaco();});

  return () => (
    <AutoTable option={option}>
      <PlcInput title={i18n.$intl('page.moduleListPage.moduleName').d('模块名称')} field="label" required width={180}/>
      <PlcInput title={i18n.$intl('page.moduleListPage.moduleCode').d('模块标识')} field="code" required/>
      <Plc title={i18n.$intl('page.moduleListPage.moduleConfig').d('模块配置')} v-slots={{
        normal: ({ row }) => <Button mode="text" label={
          row.moduleConfig?.length ?
            i18n.$intl('page.moduleListPage.editConfig').d('编辑配置') :
            i18n.$intl('page.moduleListPage.emptyConfig').d('未配置')
        } onClick={() => onClick(row)}/>
      }}/>
      <PlcTextarea title={i18n.$intl('page.moduleListPage.moduleRemarks').d('模块备注')} field="remarks" fit/>
      <PlcDate title={i18n.$intl('page.moduleListPage.createdAt').d('创建时间')} field="createdAt" hideInForm width={180} editable={false} datetime/>
      <PlcDate title={i18n.$intl('page.moduleListPage.updatedAt').d('更新时间')} field="updatedAt" hideInForm width={180} editable={false} datetime/>
    </AutoTable>
  );
});
